Search a 2D Matrix

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

For example,

Consider the following matrix:

  1. [
  2. [1, 3, 5, 7],
  3. [10, 11, 16, 20],
  4. [23, 30, 34, 50]
  5. ]

Given target = 3, return true.

Solution:

  1. public class Solution {
  2. public boolean searchMatrix(int[][] matrix, int target) {
  3. int n = matrix.length;
  4. int m = matrix[0].length;
  5. int i = 0;
  6. int j = m - 1;
  7. while (i < n && j >= 0) {
  8. if (target == matrix[i][j]) {
  9. return true;
  10. }
  11. if (target < matrix[i][j]) {
  12. j--;
  13. } else {
  14. i++;
  15. }
  16. }
  17. return false;
  18. }
  19. }